<?php

namespace App\Http\Controllers;

use App\Article;
use App\ArticleType;
use App\Product;
use App\ProductType;
use Illuminate\Http\Request;

class ListController extends Controller
{
    public function product($id)
    {
        $productTypes = ProductType::orderBy('sort', 'asc')
            ->get();
        if ($id <= 0) {
            $title = '所有产品';
            $products = Product::orderBy('created_at', 'desc')
                ->paginate(5);
        } else {
            $productType = ProductType::find($id);
            $title = $productType->name;
            $products = Product::where('type', $id)
                ->orderBy('created_at', 'desc')
                ->paginate(5);
        }
        return view('product.list', [
            'title' => $title,
            'products' => $products,
            'productTypes' => $productTypes
        ]);
    }

    public function article($id)
    {
        $articleType = ArticleType::find($id);
        $productTypes = ProductType::orderBy('sort', 'asc')
            ->get();
        $articles = Article::where('type_id', $id)
            ->orderBy('created_at', 'desc')
            ->paginate(10);
        return view('article.list', [
            'title' => $articleType->name,
            'articles' => $articles,
            'productTypes' => $productTypes
        ]);
    }

    public function search(Request $request)
    {
        $name = $request->input('name');
        if (empty($name)) {
            $products = Product::orderBy('created_at', 'desc')
                ->paginate(5);
        } else {
            $products = Product::where('name', 'like', '%'.$name.'%')
                ->orderBy('created_at', 'desc')
                ->paginate(5);
        }
        $productTypes = ProductType::orderBy('sort', 'asc')
            ->get();
        return view('product.search', [
            'products' => $products,
            'productTypes' => $productTypes
        ]);
    }
}